Popular Searches
Popular Course Categories
Popular Courses

Sorting Displayed Data

Sorting Displayed Data

Lists and Dynamic Rendering

Sorting Displayed Data in React JS

Sorting Displayed Data in React JS is the process of arranging data in a particular order, such as alphabetical order, ascending order, descending order, price, date, rating, or marks. React applications commonly use JavaScript's sort() method along with state management and event handlers to let users control how information appears on the screen.

Sorting is useful in e-commerce websites, student management systems, employee directories, dashboards, job portals, product catalogs, and data tables.

React JS Training: JustAcademy React JS Training Course

Course Demo: Register for React JS Course Demo


1. What Is Sorting Displayed Data?

Sorting displayed data means arranging the items in a list according to a specified rule. Instead of displaying information in its original order, an application can arrange it based on a property such as name, price, date, marks, or rating.

Example

Suppose an application contains the following products:

const products = [
  { id: 1, name: "Laptop", price: 55000 },
  { id: 2, name: "Mouse", price: 800 },
  { id: 3, name: "Keyboard", price: 1500 },
  { id: 4, name: "Monitor", price: 12000 }
];

If the products are sorted by price in ascending order, the displayed result becomes:

Mouse - ₹800
Keyboard - ₹1500
Monitor - ₹12000
Laptop - ₹55000

Sorting changes the order in which the data is displayed. It does not necessarily add, remove, or change the actual product information.

Common Sorting Options

  • Ascending order: Smallest to largest, A to Z, or oldest to newest.
  • Descending order: Largest to smallest, Z to A, or newest to oldest.
  • Alphabetical sorting: Arranges text according to the selected language's alphabetical rules.
  • Numeric sorting: Arranges numbers based on their numerical values.
  • Date sorting: Arranges records by date or time.
  • Property-based sorting: Sorts objects by properties such as price, name, marks, or rating.

2. What Is the JavaScript sort() Method?

The sort() method is a built-in JavaScript array method used to arrange array elements. By default, it sorts values as strings. To sort numbers or object properties correctly, you generally provide a comparison function.

Syntax

array.sort(compareFunction);

The comparison function is optional. When supplied, it determines which of two elements should appear first.

How the Comparison Function Works

(a, b) => a - b
Return Value Meaning
Negative number Place a before b.
Positive number Place a after b.
Zero Treat both values as equal for sorting.

The sort() method sorts the array in place, meaning it changes the original array. In React, you should generally sort a copy of state or props data rather than mutating the original array.


3. Sorting Numbers in Ascending Order

Ascending order arranges numbers from the smallest value to the largest value.

Example

const numbers = [50, 10, 40, 20, 30];

const sortedNumbers = [...numbers].sort(
  (a, b) => a - b
);

console.log(sortedNumbers);

Output:

[10, 20, 30, 40, 50]

Explanation

  • The spread operator [...numbers] creates a shallow copy of the array.
  • The sort() method arranges the copied numbers.
  • The comparison function (a, b) => a - b places smaller numbers before larger numbers.
  • The original numbers array remains unchanged.

4. Sorting Numbers in Descending Order

Descending order arranges numbers from the largest value to the smallest value.

Example

const numbers = [50, 10, 40, 20, 30];

const sortedNumbers = [...numbers].sort(
  (a, b) => b - a
);

console.log(sortedNumbers);

Output:

[50, 40, 30, 20, 10]

Using b - a reverses the numerical ordering produced by a - b.


5. Why Is a Comparison Function Important?

Without a comparison function, JavaScript's sort() method converts array elements to strings and compares them by their character codes. This can produce unexpected results when sorting numbers.

Incorrect Numeric Sorting

const numbers = [1, 10, 2, 30, 4];

console.log([...numbers].sort());

Output:

[1, 10, 2, 30, 4]

This is not numerical ascending order because the values are compared as strings.

Correct Numeric Sorting

const numbers = [1, 10, 2, 30, 4];

console.log([...numbers].sort((a, b) => a - b));

Output:

[1, 2, 4, 10, 30]

Remember: Use (a, b) => a - b for ascending numeric order and (a, b) => b - a for descending numeric order.


6. Sorting Strings Alphabetically

Strings can be sorted alphabetically using sort(). For more predictable text sorting, especially when case and language conventions matter, use localeCompare().

Example

const names = ["Rahul", "Amit", "Neha", "Priya"];

const sortedNames = [...names].sort((a, b) =>
  a.localeCompare(b)
);

console.log(sortedNames);

Output:

["Amit", "Neha", "Priya", "Rahul"]

Descending Alphabetical Order

const sortedNames = [...names].sort((a, b) =>
  b.localeCompare(a)
);

This arranges the names in reverse alphabetical order.


7. Sorting an Array of Objects

React applications frequently display arrays of objects. Each object contains properties such as a name, price, marks, rating, or date. You can sort these objects by comparing the value of the relevant property.

Example: Sort Students by Marks

const students = [
  { id: 1, name: "Rahul", marks: 75 },
  { id: 2, name: "Priya", marks: 92 },
  { id: 3, name: "Amit", marks: 68 },
  { id: 4, name: "Neha", marks: 85 }
];

const sortedStudents = [...students].sort(
  (a, b) => a.marks - b.marks
);

console.log(sortedStudents);

Result: Amit, Rahul, Neha, and Priya, from lowest marks to highest marks.

Sort Students by Name

const sortedStudents = [...students].sort(
  (a, b) => a.name.localeCompare(b.name)
);

When sorting objects, the comparison function should compare the property you want to use for ordering.


8. Sorting Displayed Data in React Using useState()

The useState() Hook can store the selected sorting option. When a user changes the option, React updates the state and renders the data in the selected order.

Example: Sort a Student List

import { useState } from "react";

const students = [
  { id: 1, name: "Rahul", marks: 75 },
  { id: 2, name: "Priya", marks: 92 },
  { id: 3, name: "Amit", marks: 68 },
  { id: 4, name: "Neha", marks: 85 }
];

function StudentList() {
  const [sortOrder, setSortOrder] = useState("name-asc");

  const sortedStudents = [...students].sort((a, b) => {
    if (sortOrder === "name-asc") {
      return a.name.localeCompare(b.name);
    }

    if (sortOrder === "name-desc") {
      return b.name.localeCompare(a.name);
    }

    if (sortOrder === "marks-asc") {
      return a.marks - b.marks;
    }

    if (sortOrder === "marks-desc") {
      return b.marks - a.marks;
    }

    return 0;
  });

  return (
    <div>
      <h2>Student List</h2>
      <label htmlFor="sortOrder">Sort students: </label>
      <select
        id="sortOrder"
        value={sortOrder}
        onChange={event => setSortOrder(event.target.value)}
      >
        <option value="name-asc">Name: A to Z</option>
        <option value="name-desc">Name: Z to A</option>
        <option value="marks-asc">Marks: Low to High</option>
        <option value="marks-desc">Marks: High to Low</option>
      </select>
      <ul>
        {sortedStudents.map(student => (
          <li key={student.id}>
            {student.name} - {student.marks} marks
          </li>
        ))}
      </ul>
    </div>
  );
}

export default StudentList;

How It Works

  1. The student data is stored in an array of objects.
  2. The sortOrder state stores the selected sorting option.
  3. The onChange event updates the state when a user selects an option.
  4. The array is copied using the spread operator before sorting.
  5. The comparison function sorts the data according to the selected option.
  6. The map() method renders the sorted students.
  7. Each list item uses the student's stable ID as its React key.

9. Sorting Products by Price

Sorting products by price is a common feature in online shopping applications. Users may want to see the cheapest products first or the most expensive products first.

Example: Product Sorting

import { useState } from "react";

const products = [
  { id: 1, name: "Laptop", price: 55000 },
  { id: 2, name: "Mouse", price: 800 },
  { id: 3, name: "Keyboard", price: 1500 },
  { id: 4, name: "Monitor", price: 12000 }
];

function ProductList() {
  const [sortOrder, setSortOrder] = useState("low-to-high");

  const sortedProducts = [...products].sort((a, b) => {
    return sortOrder === "low-to-high"
      ? a.price - b.price
      : b.price - a.price;
  });

  return (
    <div>
      <h2>Products</h2>
      <select
        value={sortOrder}
        onChange={event => setSortOrder(event.target.value)}
      >
        <option value="low-to-high">Price: Low to High</option>
        <option value="high-to-low">Price: High to Low</option>
      </select>
      <ul>
        {sortedProducts.map(product => (
          <li key={product.id}>
            {product.name} - ₹{product.price.toLocaleString("en-IN")}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ProductList;

The dropdown controls the sorting direction. The product list automatically changes when the selected option changes.


10. Sorting Dates in React

Dates can be sorted from oldest to newest or newest to oldest. When dates are stored as valid date strings, you can convert them to timestamps for comparison.

Example

const events = [
  { id: 1, name: "Workshop", date: "2026-08-10" },
  { id: 2, name: "Conference", date: "2026-06-15" },
  { id: 3, name: "Training", date: "2026-09-20" }
];

// Oldest to newest
const ascendingEvents = [...events].sort(
  (a, b) => new Date(a.date) - new Date(b.date)
);

// Newest to oldest
const descendingEvents = [...events].sort(
  (a, b) => new Date(b.date) - new Date(a.date)
);

Use consistent, valid date formats such as ISO date strings when possible. If dates may be missing or invalid, validate them before sorting.


11. Sorting Data with Buttons

Instead of using a dropdown, you can provide buttons that let users switch between ascending and descending order.

Example

import { useState } from "react";

const numbers = [40, 10, 30, 20];

function NumberList() {
  const [ascending, setAscending] = useState(true);

  const sortedNumbers = [...numbers].sort((a, b) =>
    ascending ? a - b : b - a
  );

  return (
    <div>
      <button onClick={() => setAscending(true)}>
        Ascending
      </button>
      <button onClick={() => setAscending(false)}>
        Descending
      </button>
      <ul>
        {sortedNumbers.map(number => (
          <li key={number}>{number}</li>
        ))}
      </ul>
    </div>
  );
}

export default NumberList;

Each button updates the sorting direction. React then renders the numbers in the selected order.


12. Sorting Table Data in React

Tables are commonly used to display structured information such as employee records, student marks, orders, and financial data. Sorting table rows makes it easier to find and compare records.

Example: Sort Employees by Salary

import { useState } from "react";

const employees = [
  { id: 1, name: "Amit", salary: 45000 },
  { id: 2, name: "Priya", salary: 60000 },
  { id: 3, name: "Rahul", salary: 35000 }
];

function EmployeeTable() {
  const [ascending, setAscending] = useState(true);

  const sortedEmployees = [...employees].sort((a, b) =>
    ascending ? a.salary - b.salary : b.salary - a.salary
  );

  return (
    <div>
      <button onClick={() => setAscending(value => !value)}>
        Sort Salary {ascending ? "High to Low" : "Low to High"}
      </button>
      <table border="1" cellPadding="8" cellSpacing="0">
        <thead>
          <tr>
            <th>Name</th>
            <th>Salary</th>
          </tr>
        </thead>
        <tbody>
          {sortedEmployees.map(employee => (
            <tr key={employee.id}>
              <td>{employee.name}</td>
              <td>₹{employee.salary.toLocaleString("en-IN")}</td>
            </tr>
          ))}
        </tbody>
      </table>
    </div>
  );
}

export default EmployeeTable;

Note: The button text should describe the action or the current sorting state clearly. You can adjust the label to match your preferred interaction design.


13. Combining Filtering and Sorting

In real applications, users often want to filter data and then sort the matching results. For example, an online store may allow users to select a category and sort the products by price.

Example

const filteredAndSortedProducts = [...products]
  .filter(product =>
    selectedCategory === "All" ||
    product.category === selectedCategory
  )
  .sort((a, b) =>
    sortOrder === "low-to-high"
      ? a.price - b.price
      : b.price - a.price
  );

Explanation:

  • filter() selects products matching the category.
  • The spread operator creates a copy of the original array.
  • sort() arranges the filtered products by price.
  • The final array can be rendered using map().

For predictable behavior, make sure the sorting operation works on a copy rather than directly mutating the source data.


14. Sorting Without Mutating the Original Array

JavaScript's sort() method modifies the array on which it is called. This matters in React because props and state should not be mutated directly.

Method 1: Use the Spread Operator

const numbers = [30, 10, 20];

const sortedNumbers = [...numbers].sort(
  (a, b) => a - b
);

console.log(numbers);        // [30, 10, 20]
console.log(sortedNumbers);  // [10, 20, 30]

Method 2: Use toSorted()

const numbers = [30, 10, 20];

const sortedNumbers = numbers.toSorted(
  (a, b) => a - b
);

console.log(numbers);        // [30, 10, 20]
console.log(sortedNumbers);  // [10, 20, 30]

The toSorted() method returns a new sorted array without modifying the original array. It is supported in modern JavaScript environments; use a spread-copy with sort() when your target environment does not support toSorted().

Comparison

Method Changes Original Array? Creates a New Sorted Array?
array.sort() Yes No
[...array].sort() No Yes, by sorting a copy
array.toSorted() No Yes

15. Sorting Data Using useMemo()

When sorting large lists or performing expensive calculations, React's useMemo() Hook can help avoid repeating the sorting calculation when its dependencies have not changed.

Example

import { useMemo, useState } from "react";

function ProductList({ products }) {
  const [sortOrder, setSortOrder] = useState("low-to-high");

  const sortedProducts = useMemo(() => {
    return [...products].sort((a, b) =>
      sortOrder === "low-to-high"
        ? a.price - b.price
        : b.price - a.price
    );
  }, [products, sortOrder]);

  return (
    <div>
      <select
        value={sortOrder}
        onChange={event => setSortOrder(event.target.value)}
      >
        <option value="low-to-high">Price: Low to High</option>
        <option value="high-to-low">Price: High to Low</option>
      </select>
      <ul>
        {sortedProducts.map(product => (
          <li key={product.id}>
            {product.name} - ₹{product.price}
          </li>
        ))}
      </ul>
    </div>
  );
}

export default ProductList;

useMemo() recalculates the sorted array when products or sortOrder changes. It is an optimization rather than a requirement for every list, and the parent should avoid unnecessarily creating a new products array on every render if memoization is important.


16. Sorting API Data in React

React applications often receive data from an API. After the data is loaded into state, you can sort it before displaying it.

Example

import { useEffect, useState } from "react";

function UserList() {
  const [users, setUsers] = useState([]);
  const [sortOrder, setSortOrder] = useState("asc");
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState("");

  useEffect(() => {
    const controller = new AbortController();

    async function fetchUsers() {
      try {
        const response = await fetch(
          "https://jsonplaceholder.typicode.com/users",
          { signal: controller.signal }
        );

        if (!response.ok) {
          throw new Error("Failed to fetch users.");
        }

        const data = await response.json();
        setUsers(data);
      } catch (err) {
        if (err.name !== "AbortError") {
          setError(err.message || "Something went wrong.");
        }
      } finally {
        if (!controller.signal.aborted) {
          setLoading(false);
        }
      }
    }

    fetchUsers();

    return () => controller.abort();
  }, []);

  const sortedUsers = [...users].sort((a, b) =>
    sortOrder === "asc"
      ? a.name.localeCompare(b.name)
      : b.name.localeCompare(a.name)
  );

  if (loading) return <p>Loading users...</p>;
  if (error) return <p>Error: {error}</p>;

  return (
    <div>
      <h2>User Directory</h2>
      <select
        value={sortOrder}
        onChange={event => setSortOrder(event.target.value)}
      >
        <option value="asc">Name: A to Z</option>
        <option value="desc">Name: Z to A</option>
      </select>
      <ul>
        {sortedUsers.map(user => (
          <li key={user.id}>{user.name}</li>
        ))}
      </ul>
    </div>
  );
}

export default UserList;

Explanation

  • useEffect() retrieves the users when the component mounts.
  • useState() stores the API data, sorting order, loading state, and error state.
  • [...users].sort() creates and sorts a copy of the user array.
  • localeCompare() compares user names alphabetically.
  • The dropdown updates the sorting order.
  • The loading and error messages provide feedback while the API request is processed.

17. Sorting by Multiple Properties

Sometimes two records have the same primary value. You can use a secondary property to determine the order when the primary values are equal.

Example: Sort by Department, Then by Name

const employees = [
  { id: 1, name: "Rahul", department: "IT" },
  { id: 2, name: "Amit", department: "HR" },
  { id: 3, name: "Priya", department: "IT" },
  { id: 4, name: "Neha", department: "HR" }
];

const sortedEmployees = [...employees].sort((a, b) => {
  const departmentComparison =
    a.department.localeCompare(b.department);

  if (departmentComparison !== 0) {
    return departmentComparison;
  }

  return a.name.localeCompare(b.name);
});

This sorts employees by department first. When two employees belong to the same department, their names are sorted alphabetically.


18. Common Mistakes While Sorting Data

Mistake Problem Correct Approach
Using sort() without a comparison function for numbers Numbers may be sorted as strings. Use (a, b) => a - b or (a, b) => b - a.
Sorting a state or props array directly The original array is mutated. Sort a copy using [...array].sort() or use toSorted().
Using the wrong property The list may be ordered by an unintended value. Compare the correct property, such as a.price - b.price.
Not updating the sorting state The user cannot change the sorting order. Connect the dropdown or button to a state setter.
Missing React keys React may show a key warning and track list items less reliably. Use stable IDs such as key={item.id}.
Incorrect date comparison Dates may appear in an unexpected order. Compare validated timestamps or valid date values.
Assuming all values are present Missing or invalid properties can produce unexpected ordering. Validate data and define a policy for missing values.
Overusing useMemo() Code becomes more complex without meaningful performance benefits. Use memoization when measurement or data size justifies it.

19. Best Practices for Sorting Displayed Data

  • Use a comparison function for numerical values.
  • Use localeCompare() for text sorting when appropriate.
  • Never mutate React state or props arrays directly.
  • Use [...array].sort() or toSorted() to create a new sorted array.
  • Store the user's selected sorting option in React state.
  • Use descriptive names such as sortedProducts and sortOrder.
  • Use stable IDs for list keys rather than relying on array indexes.
  • Handle missing, invalid, or inconsistent values when sorting external data.
  • Combine sorting with filtering when the interface needs both features.
  • Use useMemo() only when it provides a useful optimization.
  • Make sorting controls accessible with clear labels and appropriate form elements.
  • For very large datasets, consider server-side sorting, pagination, or list virtualization.

20. Real-World Applications of Sorting

  • E-commerce websites: Sort products by price, rating, popularity, or name.
  • Student management systems: Sort students by name, marks, grade, or attendance.
  • Employee dashboards: Sort employees by salary, department, or joining date.
  • Job portals: Sort job listings by date posted, salary, or relevance.
  • Booking platforms: Sort hotels by price, rating, or distance.
  • Admin dashboards: Sort records by status, date, or priority.
  • Financial applications: Sort transactions by amount or date.
  • Educational platforms: Sort courses by title, duration, or popularity.

21. Mini Project: Product Sorting Application

Project Objective: Create a React component that displays products and allows users to sort them by price or name.

Project Requirements

  • Create an array of products with id, name, category, and price.
  • Display the products using map().
  • Add a dropdown for sorting by price from low to high.
  • Add an option for sorting by price from high to low.
  • Add alphabetical sorting options for product names.
  • Store the selected option in state using useState().
  • Sort a copy of the array instead of mutating the original data.
  • Use a unique product ID as the React key.
  • Display each product's name, category, and price.

Sample Product Data

const products = [
  { id: 1, name: "Laptop", category: "Electronics", price: 55000 },
  { id: 2, name: "Mouse", category: "Accessories", price: 800 },
  { id: 3, name: "Keyboard", category: "Accessories", price: 1500 },
  { id: 4, name: "Monitor", category: "Electronics", price: 12000 },
  { id: 5, name: "Headphones", category: "Accessories", price: 2500 }
];

Expected Result

When the user selects “Price: Low to High”, the mouse appears first. When the user selects “Price: High to Low”, the laptop appears first. When the user selects “Name: A to Z”, products appear alphabetically by name.

Skills Practiced

  • JavaScript array sorting
  • React state management
  • Controlled dropdowns
  • Event handling
  • Rendering arrays with map()
  • Sorting arrays of objects
  • Immutable data handling

22. Interview Questions and Answers

Q1. What is sorting in React JS?

Answer: Sorting in React JS means arranging displayed data according to a particular order, such as alphabetical order, price, marks, or date.

Q2. Which JavaScript method is used to sort an array?

Answer: The sort() method is used to arrange array elements. A comparison function can define the sorting order.

Q3. How do you sort numbers in ascending order?

Answer: Use array.sort((a, b) => a - b). In React, sort a copy of the array to avoid modifying the original.

Q4. How do you sort numbers in descending order?

Answer: Use array.sort((a, b) => b - a) on a copy when the original array must remain unchanged.

Q5. Does sort() modify the original array?

Answer: Yes. The sort() method sorts the array in place and returns a reference to that same array.

Q6. How can you sort an array without modifying the original?

Answer: Use [...array].sort() or array.toSorted(). The latter returns a new sorted array in supported JavaScript environments.

Q7. How do you sort an array of objects by price?

Answer: Use a comparison function such as [...products].sort((a, b) => a.price - b.price).

Q8. How do you implement a sorting dropdown in React?

Answer: Store the selected option in state using useState(), update it through the dropdown's onChange handler, and calculate the sorted array from that state.

Q9. What is the difference between sort() and toSorted()?

Answer: sort() modifies the original array, whereas toSorted() returns a new sorted array without modifying the original.

Q10. How can you sort strings alphabetically?

Answer: Use sort((a, b) => a.localeCompare(b)) for locale-aware string comparison.

Q11. Can sorting be combined with filtering?

Answer: Yes. Filter the source data to select matching items, then sort a copy of the resulting array before rendering it.

Q12. Why might useMemo() be useful for sorting?

Answer: It can cache an expensive sorting calculation and recalculate it when the relevant dependencies change. It is an optimization, not a requirement for every list.


23. Practice Exercises

  1. Create an array of numbers and display them in ascending order.
  2. Sort the same array in descending order.
  3. Create a list of student objects and sort them alphabetically by name.
  4. Sort student records by marks from highest to lowest.
  5. Create a product list and sort products by price.
  6. Add a dropdown that lets users choose the sorting order.
  7. Create an employee table and sort employees by salary.
  8. Sort event records by date from oldest to newest.
  9. Combine category filtering and price sorting in a product list.
  10. Fetch records from an API and add a sorting dropdown.
  11. Sort employees by department and then by name.
  12. Use useMemo() to optimize sorting for a large product array.

24. Quick Revision Checklist

  • Understand the purpose of sorting displayed data.
  • Know how JavaScript's sort() method works.
  • Understand comparison functions.
  • Sort numbers in ascending and descending order.
  • Sort strings alphabetically.
  • Sort arrays of objects by their properties.
  • Use useState() to control sorting options.
  • Render sorted data using map().
  • Avoid mutating arrays stored in React state or passed as props.
  • Understand the difference between sort() and toSorted().
  • Combine sorting with filtering when needed.
  • Know when memoization or server-side sorting may be helpful.

25. Conclusion

Sorting Displayed Data is an important React JS concept that helps developers organize information in a meaningful order. By using JavaScript's sort() method, comparison functions, React state, event handlers, and array rendering, you can build interactive product catalogs, student lists, employee tables, and dashboards.

Always avoid mutating state or props directly. Create a sorted copy of the array, update the sorting state when users interact with controls, and render the results using stable React keys.

Learn More: JustAcademy React JS Training Course

Register for a Demo: Register for React JS Course Demo

whatsapp